package com.xiaochi.wx.handler;

import com.xiaochi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zqx
 * @since 2024/8/31
 */
@Component
@Slf4j
public class ReceiveTextMsgType implements WxChatMsgHandler{

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxchatMsgTypeEnum getMsgType() {
        return WxchatMsgTypeEnum.TEXT;
    }

    @Override
    public String dealMsg(Map<String, String> messMap) {
        log.info("用户消息事件");
        String content = messMap.get("Content");
        String fromUserName = messMap.get("FromUserName");
        String toUserName = messMap.get("ToUserName");
        if (!KEY_WORD.equals(content)){
            return "";
        }
        Random random = new Random();
        int num = random.nextInt(1000);
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
        redisUtil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);
        String numContent = "你的验证码是:"+ num +"五分钟有效";
        String msg = "<xml>\n" +
                "  <ToUserName><![CDATA["+ fromUserName +"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+ toUserName +"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+ numContent+ "]]></Content>\n" +
                "</xml>";
        return msg;
    }
}
